<template>
  <BasicModal style="display: inline-block" v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { accountFormSchema } from './account.data';
  import { getDepartmentOption } from '@/api/sys/department';
  import { exitsPhone, saveUserApi } from '@/api/sys/user';

  defineOptions({ name: 'AccountModal' });

  const emit = defineEmits(['success', 'register']);

  const isUpdate = ref(true);
  const rowId = ref('');

  const [registerForm, { setFieldsValue, updateSchema, resetFields, validate }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: accountFormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      rowId.value = data.record.id;
      setFieldsValue({
        ...data.record,
      });
    }

    const treeData = await getDepartmentOption();
    updateSchema([
      {
        field: 'phone',
        label: '手机号',
        component: 'Input',
        helpMessage: ['异步验证手机号是否重复'],
        rules: [
          {
            required: true,
            message: '请输入手机号码',
          },
          {
            trigger: 'blur',
            validator(_, value) {
              return new Promise((resolve, reject) => {
                if (!value) return resolve();
                exitsPhone({
                  phone: value,
                  type: unref(isUpdate),
                })
                  .then(resolve)
                  .catch((err) => {
                    reject(err.message || '验证失败');
                  });
              });
            },
          },
        ],
        dynamicDisabled: unref(isUpdate),
      },
      {
        field: 'department',
        componentProps: { treeData },
      },
    ]);
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增账号' : '编辑账号'));

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      if (unref(isUpdate)) {
        values.id = rowId.value;
      }
      // 异步调用编辑接口
      await saveUserApi(values);
      closeModal();
      emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
